<?php
// +----------------------------------------------------------------------
// | Description: 公共模型,所有模型都可继承此模型，基于RESTFUL CRUD操作
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\admin\lib\enum\ApplyStatus;
use app\v2\model\Apply;
use app\v2\model\Order;
use think\Db;
use think\Model;

class Common extends Model
{

    /**
     * [getDataById 根据主键获取详情]
     * @linchuangbin
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {
        $data = $this->get($id);
        if (!$data) {
            $this->error = '暂无此数据';
            return false;
        }
        return $data;
    }

    /**
     * [createData 新建]
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param)
    {

        // 验证
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        try {
            $this->data($param)->allowField(true)->save();
            return true;
        } catch (\Exception $e) {
            $this->error = '添加失败';
            return false;
        }
    }

    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param     [type]                   $param [description]
     * @param     [type]                   $id    [description]
     * @return    [type]                          [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }

        // 验证
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }

        try {
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            return true;
        } catch (\Exception $e) {
            $this->error = '编辑失败';
            return false;
        }
    }

    /**
     * [delDataById 根据id删除数据]
     * @linchuangbin
     * @DateTime  2017-02-11T20:57:55+0800
     * @param     string $id [主键]
     * @param     boolean $delSon [是否删除子孙数据]
     * @return    [type]                           [description]
     */
    public function delDataById($id = '', $delSon = false)
    {

        $this->startTrans();
        try {
            $this->where($this->getPk(), $id)->delete();
            if ($delSon && is_numeric($id)) {
                // 删除子孙
                $childIds = $this->getAllChild($id);
                if ($childIds) {
                    $this->where($this->getPk(), 'in', $childIds)->delete();
                }
            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = '删除失败';
            $this->rollback();
            return false;
        }
    }

    /**
     * [delDatas 批量删除数据]
     * @linchuangbin
     * @DateTime  2017-02-11T20:59:34+0800
     * @param     array $ids [主键数组]
     * @param     boolean $delSon [是否删除子孙数据]
     * @return    [type]                          [description]
     */
    public function delDatas($ids = [], $delSon = false)
    {
        if (empty($ids)) {
            $this->error = '删除失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon) {
            foreach ($ids as $k => $v) {
                if (!is_numeric($v)) continue;
                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }

        try {
            $this->where($this->getPk(), 'in', $ids)->delete();
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }

    }

    /**
     * [enableDatas 批量启用、禁用]
     * @AuthorHTL
     * @DateTime  2017-02-11T21:01:58+0800
     * @param     string $ids [主键数组]
     * @param     integer $status [状态1启用0禁用]
     * @param     [boolean]                $delSon [是否删除子孙数组]
     * @return    [type]                           [description]
     */
    public function enableDatas($ids = [], $status = 1,$type, $delSon = false)
    {

      
       if($status ==0)
        {

            foreach ($ids as $key1 => $value1) {
               $info =  Db::name('binvite_code')->field('bid,bname,bcode')->where(['bid'=>$value1])->find();
   
               if($info)
               {
                 $bcode =  Db::name('binvite_not_code')->where(['bid'=>$info['bid']])->find();
                 if($bcode)
                 {
                    $data = ['bcode'=>$info['bcode'],'bname'=>$info['bname']];
                    Db::name('binvite_not_code')->where(['bid'=>$info['bid']])->update($data);
                 }else {
                    $data = ['bcode'=>$info['bcode'],'bname'=>$info['bname'],'bid'=>$info['bid']];
                    Db::name('binvite_not_code')->insert($data);
                 }
               }
            }
        }


       if($status ==1)
        {
            foreach ($ids as $key2 => $value2) {
               $res =  Db::name('binvite_not_code')->where(['bid'=>$value2])->delete();  
            }
        }


        if (empty($ids)) {
            $this->error = '修改失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon && $status === '0') {
            foreach ($ids as $k => $v) {
                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }
        try {
            $this->where($this->getPk(), 'in', $ids)->setField('status', $status);
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }

    /**
     * 获取所有子孙
     */
    public function getAllChild($id, &$data = [])
    {
        $map['pid'] = $id;
        $childIds = $this->where($map)->column($this->getPk());
        if (!empty($childIds)) {
            foreach ($childIds as $v) {
                $data[] = $v;
                $this->getAllChild($v, $data);
            }
        }
        return $data;
    }

    /**
     * 获取用户所属所有用户组
     * @param  array $param [description]
     */
    public function groups()
    {
        return $this->belongsToMany('group', '__ADMIN_ACCESS__', 'group_id', 'user_id');
    }


    /**
     * 状态对应文字信息
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-07T18:19:52+0800
     * @param    integer $status 状态码
     * @return   string   文字
     */
    public function statusInfo($status)
    {
        switch ($status) {
            case 0:
                $info = '申请';
                break;
            case 1:
                $info = '初审通过';
                break;
            case 2:
                $info = '复审通过';
                break;
            case 3:
                $info = '已放款';
                break;
            case 4:
                $info = '逾期中';
                break;
            case 5:
                $info = '已完成';
                break;
            case 6:
                $info = '初审驳回';
                break;
            case 7:
                $info = '复审驳回';
                break;
            case 8:
                $info = '其它驳回';
                break;
            case 9:
                $info = '回访通过';
                break;
            case 10:
                $info = '回访拒绝';
                break;
            case 11:
                $info = '拒绝放款';
                break;
            case 12:
                $info = '已经延期';
                break;
            default:
                $info = '未知状态';
                break;
        }
        return $info;
    }

    /**
     * 根据管理员id查询管理员名称
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-07T18:10:44+0800
     * @param    integer $uid 管理员id
     * @return   string
     */
    public function getNameById($uid)
    {
        $name = Db::name('admin_user')->where('id', $uid)->value('realname');
        return $name ? $name : '';
    }

    /**
     * 根据状态查询驳回操作人
     * @author   cxr <1481746137@qq.com>
     * @return   string
     */
    public function getRefuseByStatus($info)
    {
        switch ($info['status']) {
            case ApplyStatus::FIRST_REFUSE:
                $uid = $info['check_aid'];
                break;
            case ApplyStatus::REVIEW_REFUSE:
                $uid = $info['check2_aid'];
                break;
            case ApplyStatus::OTHER_REFUSE:
                $uid = $info['check_aid'];
                break;
            case ApplyStatus::RETURN_REFUSE:
                $uid = $info['merchandiser'];
                break;
            case ApplyStatus::LEND_REFUSE:
                $uid = $info['treasurer'];
                break;
        }
        $name = Db::name('admin_user')->where('id', $uid)->value('username');
        return $name ? $name : '';
    }

    public function getPersonByStatus($info)
    {
        switch ($info['status']) {
            case ApplyStatus::FIRST_REFUSE:
                $uid = $info['check_aid']['username'];
                break;
            case ApplyStatus::REVIEW_REFUSE:
                $uid = $info['check2_aid']['username'];
                break;
            case ApplyStatus::OTHER_REFUSE:
                $uid = $info['check_aid']['username'];
                break;
            case ApplyStatus::RETURN_REFUSE:
                $uid = $info['merchandiser']['username'];
                break;
            case ApplyStatus::LEND_REFUSE:
                $uid = $info['treasurer']['username'];
                break;
        }
        return $uid ? $uid : '';
    }

    public function getRefuseTimeByStatus($info)
    {
        switch ($info['status']) {
            case ApplyStatus::FIRST_REFUSE:
                $uid = $info['check_time'];
                break;
            case ApplyStatus::REVIEW_REFUSE:
                $uid = $info['check2_time'];
                break;
            case ApplyStatus::OTHER_REFUSE:
                $uid = $info['time'];
                break;
            case ApplyStatus::RETURN_REFUSE:
                $uid = $info['monepassdate'];
                break;
            case ApplyStatus::LEND_REFUSE:
                $uid = $info['lendmoneydate'];
                break;
        }
//        $where['apply_id'] = $info['id'];
//        $where['status'] = 0;//拒绝
//
//        $name = Db::name('admin_user_clien')->where($where)->order("date desc")->value('date');

        return $uid ? $uid : '';
    }

    /**
     * 逾期处理  若逾期则将状态更改成逾期4
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-08T15:03:32+0800
     * @param    integer $id 申请订单id
     * @param    string $date 约定还款日期 datetime格式
     * @param    integer $status 状态码
     * @return   integer   状态码 逾期会返回4
     */
    public function setOverdue($id, $date, $status)
    {
//        try {
//            $now = time();
//            $time = strtotime($date);
//            if ($now > $time && (int)$status === 3) {
//                $status = 4;
//                $this->where('id', $id)->update(['status' => $status]);
//            }
//        } catch (\Exception $e) {
//        }
        return $status;
    }

    /**
     * 本次延期总费
     * @author cxr <1481746137@qq.com>
     * @param $status
     */
    public function getDelayMoney($value)
    {
        if (!in_array($value['status'], [3, 4, 12])) {
            return '';
        }
        $delayMoney = model('v2/Apply');
        $days = ['one' => 1,'two' => 2,'third' => 3,'seven' => 7];

        #各天数延期费
        $totalMoney = [];
        foreach ($days as $k => $v) {
            $money = $delayMoney->delayMoney($value, $v);
            $totalMoney[$k] = $money['money_order'];
        }
        return $totalMoney;
    }

    /**
     * 剩余应还
     * @author cxr <1481746137@qq.com>
     * @return int
     */
    public function getSurplus($value, $status)
    {
        if ($status == 5) {
            return 0;
        }
        return $value;
    }

    /**
     * 返回应还金额
     * @author cxr <1481746137@qq.com>
     * @return float
     */
    public function getRepay($status, $money, $repay_money)
    {
//        if ($status == 5) {
//            return $repay_money;
//        }

//        define(SYS_TIMESTAMP,time());
        $delayMoney = (new Apply())->loanMoney($money);
        $totalMoney = $delayMoney['money_order'];
        return $totalMoney;
    }

    /**
     *  逾期天数
     * @author cxr <1481746137@qq.com>
     */
    public function getOverdueDay($appoint_time){
        $appoint_time = $appoint_time['appoint_time'];
        if($appoint_time!=''||!is_null($appoint_time)){
            $times = time()-strtotime($appoint_time);
            if($times > 0){
                $overDay =   (int)ceil($times/(24*60*60)); //逾期天数
            }else{
                $overDay = 0;
            }

        }
        return $overDay;
    }
}